package com.example.choupaiapp.main.activity.home;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.dueeeke.videoplayer.player.VideoViewManager;
import com.example.choupaiapp.R;
import com.example.choupaiapp.common.ui.activity.CommonActivity;
import com.example.choupaiapp.common.util.GsonUtil;
import com.example.choupaiapp.common.util.SharedPreferencesHelp;
import com.example.choupaiapp.common.util.Utils;
import com.example.choupaiapp.main.bean.SearchLastestBean;
import com.example.choupaiapp.main.fragment.home.SearchFragment;
import com.flyco.tablayout.SlidingTabLayout;
import com.flyco.tablayout.listener.OnTabSelectListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.LinkedList;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by ASUS on 2019/11/20.
 */

public class SearchResultActivity extends CommonActivity implements ViewPager.OnPageChangeListener, OnTabSelectListener {

    @BindView(R.id.search_et)
    EditText searchEt;
    @BindView(R.id.clear)
    ImageView clear;
    @BindView(R.id.sliding_tablayout)
    SlidingTabLayout slidingTabLayout;
    @BindView(R.id.viewpager)
    ViewPager viewPager;
    private MyPagerAdapter myPagerAdapter;
    private ArrayList<Fragment> mFragments = new ArrayList<>();//存放Fragment
    private ArrayList<String> list = new ArrayList<>();
    private String name;
    private SearchLastestBean searchLastestBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_result);
    }

    @Override
    public void onTabSelect(int position) {
        viewPager.setCurrentItem(position);
    }

    @Override
    public void onTabReselect(int position) {

    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        slidingTabLayout.setmCurrentTab(position);
        slidingTabLayout.setmCurrentPositionOffset(positionOffset);
        slidingTabLayout.scrollToCurrentTab();
        slidingTabLayout.invalidate();
    }

    @Override
    public void onPageSelected(int position) {
        slidingTabLayout.updateTabSelection(position);

        VideoViewManager.instance().pause();
    }

    @Override
    public void onPageScrollStateChanged(int i) {

    }


    @Override
    protected void initView() {

        EventBus.getDefault().register(this);

        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            name = bundle.getString("name");
            searchEt.setText(name);
            clear.setVisibility(View.VISIBLE);
        }

        String lasetestjson = (String) SharedPreferencesHelp.get("Search_Lasetest", "");
        if (!TextUtils.isEmpty(lasetestjson)) {
            searchLastestBean = GsonUtil.jsonStringToClassWithGson(lasetestjson, SearchLastestBean.class);
        }

        viewPager.addOnPageChangeListener(this);
        slidingTabLayout.setOnTabSelectListener(this);

        myPagerAdapter = new MyPagerAdapter(getSupportFragmentManager());
        viewPager.setAdapter(myPagerAdapter);

        slidingTabLayout.setviewPager(viewPager);

        viewPager.setCurrentItem(0);
        viewPager.setOffscreenPageLimit(3);

        searchEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.toString().length() > 0) {
                    clear.setVisibility(View.VISIBLE);
                    EventBus.getDefault().post("search_name:" + searchEt.getText().toString().trim());
                } else {
                    clear.setVisibility(View.INVISIBLE);
                }
            }
        });

        searchEt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    //点击搜索的时候隐藏软键盘
                    InputMethodManager manager = (InputMethodManager) searchEt.getContext()
                            .getSystemService(Context.INPUT_METHOD_SERVICE);
                    manager.hideSoftInputFromWindow(searchEt.getWindowToken(), 0);

                    if (!TextUtils.isEmpty(searchEt.getText().toString().trim())) {
                        EventBus.getDefault().post("search_name:" + searchEt.getText().toString().trim());
                        if (searchLastestBean == null) {
                            searchLastestBean = new SearchLastestBean();
                            searchLastestBean.setList(new LinkedList<String>());
                        }

                        if (searchLastestBean.getList().size() > 0) {
                            if (searchLastestBean.getList().contains(searchEt.getText().toString().trim())
                                    /*&& !searchEt.getText().toString().trim().equals(searchLastestBean.getList().get(0))*/) {
                                searchLastestBean.getList().remove(searchEt.getText().toString().trim());
                            }
                        }

                        if (searchLastestBean.getList().size() >= 10) {
                            searchLastestBean.getList().remove(searchLastestBean.getList().size() - 1);
                            searchLastestBean.getList().addFirst(searchEt.getText().toString().trim());
                        } else {
                            searchLastestBean.getList().addFirst(searchEt.getText().toString().trim());
                        }
                        String json = GsonUtil.parseObjectToJsonString(searchLastestBean);
                        SharedPreferencesHelp.put("Search_Lasetest", json);

                        EventBus.getDefault().post("search_lasetest_save");

                    } else {
                        showImageToas("请输入搜索内容");
                    }
                    return true;
                }

                return false;
            }
        });
    }

    @Override
    protected void initData() {

        mFragments.add(SearchFragment.newInstance("0", name));
        list.add("全部");

        mFragments.add(SearchFragment.newInstance("2", name));
        list.add("动态");

        mFragments.add(SearchFragment.newInstance("3", name));
        list.add("专栏");

        mFragments.add(SearchFragment.newInstance("1", name));
        list.add("用户");

        myPagerAdapter.notifyDataSetChanged();
        slidingTabLayout.setmTitles(list);
        slidingTabLayout.notifyDataSetChanged();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

//    @Override
    @OnClick({R.id.clear, R.id.cancel})
    public void onViewClicked(View view) {
//        super.onViewClicked(view);
        if (Utils.isDoubleClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.clear:
                searchEt.setText("");
                break;
            case R.id.cancel:
                finishActivity();
                break;
        }
    }

    private class MyPagerAdapter extends FragmentPagerAdapter {
        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public int getCount() {
            return mFragments.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return list.get(position);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragments.get(position);
        }
    }

    @Subscribe(threadMode = ThreadMode.POSTING, sticky = true)
    public void OnMessageEvent(String event) {
        if (event.contains("skip_user")) {
            viewPager.setCurrentItem(3);
        }
    }
}
